package com.mall.order.biz.handler;


import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;

import lombok.extern.slf4j.Slf4j;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 * @Author：
 * @Date: 2019-09-16 00:03
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

	@Autowired
    private StockMapper stockMapper;

	@Override
	public boolean isAsync() {
		return false;
	}

	@Override
	@Transactional
	public boolean handle(TransHandlerContext context) {
//		// 取出和地址有关信息
//		CreateOrderContext orderContext = (CreateOrderContext) context;
//		List<CartProductDto> cartProductDtoList = orderContext.getCartProductDtoList();
//		for (CartProductDto cartProductDto : cartProductDtoList) {
//			// 取出需要的数据
//			Long limitNum = cartProductDto.getLimitNum();
//			Long productId = cartProductDto.getProductId();
//			String productName = cartProductDto.getProductName();
//			String productImg = cartProductDto.getProductImg();
//			Long productNum = cartProductDto.getProductNum();
//			BigDecimal salePrice = cartProductDto.getSalePrice();
//			// 新建stock对象
//			Stock stock = new Stock();
//			stock.setItemId(productId);
//			stock.setLockCount(Math.toIntExact(productNum));
//			stock.setStockCount(-productNum);
//			stock.setRestrictCount(limitNum.intValue());
//			// 更新
//			stockMapper.updateStock(stock);
//
//		}
//		return true;
		//向下转型
		CreateOrderContext createOrderContext = (CreateOrderContext) context;
		//获取订单商品列表
		List<CartProductDto> cartProductList = createOrderContext.getCartProductDtoList();
		//获取商品id列表(前端没传，是空的，要自己填充)
		List<Long> buyProductIds = createOrderContext.getBuyProductIds();
		if (CollectionUtils.isEmpty(buyProductIds)) {
			buyProductIds = cartProductList.stream().map(product -> product.getProductId()).collect(Collectors.toList());
		}
		//排序
		buyProductIds.sort(Long::compareTo);
		//锁定库存，sql语句中有for update ; 扣减库存，需要锁定这行库存
		List<Stock> stockList = stockMapper.findStocksForUpdate(buyProductIds);
		if (CollectionUtils.isEmpty(stockList) || stockList.size() != buyProductIds.size()) {
			log.error("SubStockHandler.handle 部分库存未初始化");
			throw new BizException("库存未初始化code未定义", "部分库存未初始化");
		}
		//扣减库存

		for (CartProductDto dto : cartProductList) {
			Long productId = dto.getProductId();
			Long productNum = dto.getProductNum();
			//productNum不能超出限购数量
			//方案 1 修改 mapper.xml实现
			//方案 2 在这里查一下
			Stock selectStock = stockMapper.selectStock(productId);
			Integer restrictNum = selectStock.getRestrictCount();
			if (productNum > restrictNum) {
				log.error("超出限购，欲够商品{},{}件,限购{}", productId, productNum, restrictNum);
				throw new BizException("超出限购code未定义", "购买数量超出限购");
			}
			Stock stockExample = new Stock();
			stockExample.setItemId(productId);
			stockExample.setStockCount(-productNum);
			stockExample.setLockCount(productNum.intValue());
			stockMapper.updateStock(stockExample);
			//这里最好能返回affectedRows,上面只怕断了限购数，
			// 没判断库存足不足，可以根据返回0说明库存不足
		}
		//传递参数给管道上下文
		createOrderContext.setBuyProductIds(buyProductIds);
		return true;
	}
}